package net.imain.cloud.controller;

import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import net.imain.cloud.dao.UserDao;
import net.imain.cloud.pojo.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author: uncle
 * @apdateTime: 2017-12-09 18:12
 */
@RestController
@RequestMapping(value = "/user/")
public class UserController {

    private static Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private EurekaClient eurekaClient;

    @Autowired
    /* 服务发现客户端 */
    private DiscoveryClient discoveryClient;

    @Autowired
    private UserDao userDao;

    /**
     * 通过用户ID查询用户信息
     *
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public User findById(@PathVariable(value = "id") Long id) {
        return userDao.findOne(id);
    }

    @GetMapping("eureka-instance")
    public String serviceUrl() {
        /* 获取实现信息 */
        InstanceInfo instance = eurekaClient.getNextServerFromEureka("service-user", false);
        /* 获取此应用名的 IP:PORT */
        return instance.getHomePageUrl();
    }

    @GetMapping("instance-info")
    public ServiceInstance serviceInstance() {
        /* 第一种 已经过时 */
//        return discoveryClient.getLocalServiceInstance();

        /* 此方法的信息更为详细 */
        List<ServiceInstance> instances = discoveryClient.getInstances("service-user");
        if (instances != null && instances.size() > 0) {
            /* 不为空 */
            for (ServiceInstance instance : instances) {
                logger.info("host: {}, port: {}, url: {}",
                        instance.getHost(), instance.getPort(), instance.getUri());
                return instance;
            }
            // return instances.get(0);
        }
        return null;
    }

    @PostMapping("testPost")
    public User testPost(User user) {
        return user;
    }
}
